package com.rds.workflow.service.impl;

import com.rds.common.core.domain.entity.SysUser;
import com.rds.common.utils.SecurityUtils;
import com.rds.system.mapper.SysUserMapper;
import com.rds.workflow.domain.RdaNodeTemplete;
import com.rds.workflow.domain.RdaWorkflow2NodeTempleteRel;
import com.rds.workflow.mapper.RdaNodeTempleteMapper;
import com.rds.workflow.mapper.RdaWorkflow2NodeTempleteRelMapper;
import com.rds.workflow.service.IRdaNodeTempleteService;
import com.rds.workflow.utils.WorkflowStateid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

@Service
public class RdaNodeTempleteServiceImpl implements IRdaNodeTempleteService {
    @Autowired
    private RdaNodeTempleteMapper rdaNodeTempleteMapper;

    @Autowired
    private RdaWorkflow2NodeTempleteRelMapper rdaWorkflow2NodeTempleteRelMapper;

    @Autowired
    private SysUserMapper sysUserMapper;


    /**
     * 类型
     */
    private static final Long typeid = 10000810L;

    /**
     * 策略
     */
    private static final Long policyid = 10000815L;

    /**
     * 流程节点创建
     */
    private static final Long nodeStateCreateid = 10000830L;


    /**
     * 流程节点活动
     */
    //private static final Long nodeStateActiveid=10000936l;

    /**
     * 流程节点完成
     */
    //private static final Long nodeStateCompleteid=10000937l;

    /**
     * 流程节点作废
     */
    //private static final Long nodeStateObsoletedid=10000938l;

    /**
     * 查询流程节点
     *
     * @param id 节点ID
     * @return 流程节点
     */
    @Override
    public RdaNodeTemplete selectRdaNodeTempleteById(Long id) {
        RdaNodeTemplete rdaNodeTemplete=rdaNodeTempleteMapper.selectRdaNodeTempleteById(id);
        RdaNodeTemplete rdaNodeTemplete2=rdaNodeTempleteMapper.selectRdaNodeTempleteByNodeid(rdaNodeTemplete.getWorkflowid(),id);
        if(rdaNodeTemplete2.getFromidArray()!=null){
            Long[] fromids=getLongArrayFromStringArray(rdaNodeTemplete2.getFromidArray().replaceAll(" ","").split(","));
            rdaNodeTemplete2.setSuperiorNodeIds(fromids);
        }
        if(rdaNodeTemplete2.getToidArray()!=null){
            Long[] toids=getLongArrayFromStringArray(rdaNodeTemplete2.getToidArray().replaceAll(" ","").split(","));
            rdaNodeTemplete2.setLowerNodeIds(toids);
        }
        if(rdaNodeTemplete.isRejectTostart()){
            rdaNodeTemplete2.setIsRejectTostart("1");
        }else{
            rdaNodeTemplete2.setIsRejectTostart("2");
        }
        if(rdaNodeTemplete.isRejectAutomatic()){
            rdaNodeTemplete2.setIsRejectAutomatic("1");
        }else{
            rdaNodeTemplete2.setIsRejectAutomatic("2");
        }
        if(rdaNodeTemplete2.getUserId()!=null){
            Long[] userIds=getLongArrayFromStringArray(rdaNodeTemplete2.getUserId().replaceAll(" ","").split(","));
            rdaNodeTemplete2.setUserIds(userIds);
        }
        return rdaNodeTemplete2;
    }

    /**
     * 查询流程节点列表
     *
     * @param rdaNodeTemplete 流程节点
     * @return 流程节点集合
     */
    @Override
    public List<RdaNodeTemplete> selectRdaNodeTempleteList(RdaNodeTemplete rdaNodeTemplete) {
        List<RdaNodeTemplete> list=rdaNodeTempleteMapper.selectRdaNodeTempleteList(rdaNodeTemplete);
        return list;
    }

    @Override
    public List<RdaNodeTemplete> selectRdaNodeTemplete(Long workflowid) {
        List<RdaNodeTemplete> rdaNodeTempleteList=rdaNodeTempleteMapper.selectRdaNodeTemplete(workflowid);
        rdaNodeTempleteList.forEach((RdaNodeTemplete rdaNodeTemplete) -> {
            String fromid=rdaNodeTemplete.getFromidArray();
            String toid=rdaNodeTemplete.getToidArray();

            String fromNameArray = "";
            String toNameArray = "";
            if(fromid!=null){
                List<RdaNodeTemplete> fromNameList=rdaNodeTempleteMapper.selectRdaNodeTempleteByInId(fromid);
                for (RdaNodeTemplete rdaNodeTemplete2:fromNameList){
                    fromNameArray+=rdaNodeTemplete2.getNodeName()+",";
                }
                rdaNodeTemplete.setFromName(fromNameArray.substring(0,fromNameArray.lastIndexOf(",")));
            }else{
                rdaNodeTemplete.setFromName("");
            }
            if(toid!=null){
                List<RdaNodeTemplete> toNameist=rdaNodeTempleteMapper.selectRdaNodeTempleteByInId(toid);
                for (RdaNodeTemplete rdaNodeTemplete3:toNameist){
                    toNameArray+=rdaNodeTemplete3.getNodeName()+",";
                }
                rdaNodeTemplete.setToName(toNameArray.substring(0,toNameArray.lastIndexOf(",")));
            }else{
                rdaNodeTemplete.setToName("");
            }
            ArrayList<String> userNames=new ArrayList<String>();
            if(null!=rdaNodeTemplete.getUserId() && rdaNodeTemplete.getUserId().length()!=0){
                String[] userIds=rdaNodeTemplete.getUserId().split(",");
                for (int i = 0; i < userIds.length; i++) {
                    String userId=userIds[i];
                    SysUser sysUser=sysUserMapper.selectUserById(Long.valueOf(userId));
                    if(sysUser!=null){
                        userNames.add(sysUser.getUserName());
                    }
                }
                Long[] userIdsI=getLongArrayFromStringArray(rdaNodeTemplete.getUserId().replaceAll(" ","").split(","));
                rdaNodeTemplete.setUserIds(userIdsI);
            }
            rdaNodeTemplete.setUserId(userNames.toString().substring(1,userNames.toString().length()-1));
            System.out.println("fromid："+fromid+"  toid："+toid+"  fromNameArray："+fromNameArray+"  toNameArray："+toNameArray);
        });

        return rdaNodeTempleteList;
    }


    /**
     * 新增流程节点
     *
     * @param rdaNodeTemplete 流程节点
     * @return 结果
     */
    @Override
    public int insertRdaNodeTemplete(RdaNodeTemplete rdaNodeTemplete) {
        Long userId = SecurityUtils.getUserId();
        rdaNodeTemplete.setOwnerid(userId.intValue());
        rdaNodeTemplete.setWorkflowid(rdaNodeTemplete.getProjectid());
        rdaNodeTemplete.setTypeid(WorkflowStateid.nodeTempleteTypeid.intValue());
        rdaNodeTemplete.setPolicyid(WorkflowStateid.nodeTempletePolicyid.intValue());
        rdaNodeTemplete.setStateid(WorkflowStateid.nodeTempleteCreateid.intValue());

        List<RdaNodeTemplete> list=rdaNodeTempleteMapper.selectRdaNodeTempleteByWorkflowid(rdaNodeTemplete.getProjectid());
        RdaNodeTemplete rdaNodeTempleteEnd=rdaNodeTempleteMapper.selectRdaNodeTempleteByNodeType(rdaNodeTemplete.getProjectid(),-1l);
        rdaNodeTemplete.setNodeType(1);
        rdaNodeTemplete.setLevel(rdaNodeTempleteEnd.getLevel());
        if("1".equals(rdaNodeTemplete.getIsRejectTostart())){
            rdaNodeTemplete.setRejectTostart(true);
        }else{
            rdaNodeTemplete.setRejectTostart(false);
        }
        if("1".equals(rdaNodeTemplete.getIsRejectAutomatic())){
            rdaNodeTemplete.setRejectAutomatic(true);
        }else{
            rdaNodeTemplete.setRejectAutomatic(false);
        }

        String userIds="";
        for(Long userIdI:rdaNodeTemplete.getUserIds()){
            userIds+=String.valueOf(userIdI)+",";
        }
        if(userIds!=null &&userIds.length()>0){
            userIds = userIds.substring(0,userIds.length()-1);
            rdaNodeTemplete.setUserId(userIds);
        }
        int num=rdaNodeTempleteMapper.insertRdaNodeTemplete(rdaNodeTemplete);
        RdaNodeTemplete updateLevel=new RdaNodeTemplete();
        updateLevel.setId(rdaNodeTempleteEnd.getId());
        updateLevel.setLevel(list.size()+1);
        rdaNodeTempleteMapper.updateRdaNodeTemplete(updateLevel);
        //插入流程关系表
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel =new RdaWorkflow2NodeTempleteRel();
        if(rdaNodeTemplete.getSuperiorNodeIds().length!=0 || rdaNodeTemplete.getLowerNodeIds().length!=0) {//当前节点新增有填上节点或下节点时

                if(rdaNodeTemplete.getSuperiorNodeIds().length!=0){//上层
                    for(int i=0;i<rdaNodeTemplete.getSuperiorNodeIds().length;i++){
                        rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getSuperiorNodeIds()[i]);
                        rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getId());
                        rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
                        rdaWorkflow2NodeTempleteRel.setOperationType("Approve");
                        rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
                    }
                }
                if(rdaNodeTemplete.getLowerNodeIds().length!=0){//下层
                    for(int i=0;i<rdaNodeTemplete.getLowerNodeIds().length;i++){
                        rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getId());//流程模板节点父id
                        rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getLowerNodeIds()[i]);
                        rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
                        rdaWorkflow2NodeTempleteRel.setOperationType("Approve");
                        rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
                    }
                }

        }
        return num;
    }


    /**
     * 新增拒绝流程节点
     *
     * @param rdaNodeTemplete 流程节点
     * @return 结果
     */
    @Override
    public int insertRdaNodeTempleteRefuse(RdaNodeTemplete rdaNodeTemplete) {
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel =new RdaWorkflow2NodeTempleteRel();
        rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getSuperiorNodeId());
        rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getLowerNodeId());
        rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getProjectid());
        rdaWorkflow2NodeTempleteRel.setOperationType("Reject");
        rdaWorkflow2NodeTempleteRel.setOperationState(0L);
        rdaWorkflow2NodeTempleteRel.setRejectScript(rdaNodeTemplete.getRejectScript());
        return rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
    }

    /**
     * 插入流程表
     * @param fromid 流程模板节点父id
     * @param toid   流程模板节点id
     * @param workflowid 流程模板ID
     * @param operationType 操作类型Approve/Reject
     * @return 结果
     */
    public int insertRdaWorkflow2NodeTempleteRel(Long fromid,Long toid,Long workflowid,String operationType){
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel =new RdaWorkflow2NodeTempleteRel();
        rdaWorkflow2NodeTempleteRel.setFromid(fromid);
        rdaWorkflow2NodeTempleteRel.setToid(toid);
        rdaWorkflow2NodeTempleteRel.setWorkflowid(workflowid);
        rdaWorkflow2NodeTempleteRel.setOperationType(operationType);
        return rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
    }
    /**
     * 修改流程节点
     *
     * @param rdaNodeTemplete 流程节点
     * @return 结果
     */
    @Override
    public int updateRdaNodeTemplete(RdaNodeTemplete rdaNodeTemplete) {
        RdaNodeTemplete rdaNodeTemplete2=rdaNodeTempleteMapper.selectRdaNodeTempleteById(rdaNodeTemplete.getId());
        rdaNodeTemplete.setWorkflowid(rdaNodeTemplete2.getWorkflowid());
        rdaWorkflow2NodeTempleteRelMapper.deleteRdaWorkflow2NodeTempleteRelById(rdaNodeTemplete.getWorkflowid(),rdaNodeTemplete.getId(),"Approve");
        RdaWorkflow2NodeTempleteRel rdaWorkflow2NodeTempleteRel =new RdaWorkflow2NodeTempleteRel();
        if(rdaNodeTemplete.getSuperiorNodeIds().length!=0 || rdaNodeTemplete.getLowerNodeIds().length!=0) {//当前节点新增有填上节点或下节点时
            if(rdaNodeTemplete.getSuperiorNodeIds().length!=0){//上层
                for(int i=0;i<rdaNodeTemplete.getSuperiorNodeIds().length;i++){
                    rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getSuperiorNodeIds()[i]);
                    rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getId());
                    rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
                    rdaWorkflow2NodeTempleteRel.setOperationType("Approve");
                    rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
                }
            }
            if(rdaNodeTemplete.getLowerNodeIds().length!=0){//下层
                for(int i=0;i<rdaNodeTemplete.getLowerNodeIds().length;i++){
                    rdaWorkflow2NodeTempleteRel.setFromid(rdaNodeTemplete.getId());//流程模板节点父id
                    rdaWorkflow2NodeTempleteRel.setToid(rdaNodeTemplete.getLowerNodeIds()[i]);
                    rdaWorkflow2NodeTempleteRel.setWorkflowid(rdaNodeTemplete.getWorkflowid());
                    rdaWorkflow2NodeTempleteRel.setOperationType("Approve");
                    rdaWorkflow2NodeTempleteRelMapper.insertRdaWorkflow2NodeTempleteRel(rdaWorkflow2NodeTempleteRel);
                }
            }
        }
        if("1".equals(rdaNodeTemplete.getIsRejectTostart())){
            rdaNodeTemplete.setRejectTostart(true);
        }else{
            rdaNodeTemplete.setRejectTostart(false);
        }
        if("1".equals(rdaNodeTemplete.getIsRejectAutomatic())){
            rdaNodeTemplete.setRejectAutomatic(true);
        }else{
            rdaNodeTemplete.setRejectAutomatic(false);
        }
        String userIds="";
        for(Long userIdI:rdaNodeTemplete.getUserIds()){
            userIds+=String.valueOf(userIdI)+",";
        }
        if(userIds!=null &&userIds.length()>0){
            userIds = userIds.substring(0,userIds.length()-1);
            rdaNodeTemplete.setUserId(userIds);
        }
        return rdaNodeTempleteMapper.updateRdaNodeTemplete(rdaNodeTemplete);
    }

    @Override
    public int updateRdaNodeTempleteAll(RdaNodeTemplete rdaNodeTemplete) {
        return rdaNodeTempleteMapper.updateRdaNodeTemplete(rdaNodeTemplete);
    }

    /**
     * 批量删除流程节点
     *
     * @param ids 需要删除的流程节点ID
     * @return 结果
     */
    @Override
    public int deleteRdaNodeTempleteByIds(Long[] ids) {
        RdaNodeTemplete rdaNodeTemplete=rdaNodeTempleteMapper.selectRdaNodeTempleteById(ids[0]);
        rdaNodeTemplete.getLevel();
        List<RdaNodeTemplete> list=rdaNodeTempleteMapper.selectRdaNodeTempleteByWorkflowid(rdaNodeTemplete.getWorkflowid());
        String id="";
        for(RdaNodeTemplete rdaNodeTempleteList:list){
            if(rdaNodeTempleteList.getLevel()>rdaNodeTemplete.getLevel()){
                id+=rdaNodeTempleteList.getId()+",";
            }
        }
        if(id!=""){
            String idN=id.substring(0,id.lastIndexOf(","));
            rdaNodeTempleteMapper.updateRdaNodeTempleteByLevel(idN);
        }
        rdaWorkflow2NodeTempleteRelMapper.deleteRdaWorkflow2NodeTempleteRelByWorkflowid(rdaNodeTemplete.getWorkflowid(),ids[0]);
        return rdaNodeTempleteMapper.deleteRdaNodeTempleteByIds(ids);
    }

    @Override
    public int insertRdaNodeTempleteStartAndEnd(RdaNodeTemplete rdaNodeTemplete) {
        rdaNodeTempleteMapper.insertRdaNodeTemplete(rdaNodeTemplete);
        return 0;
    }

    /**
     * 更新级别、序号程序入口
     * @param level 层级
     * @param parentid 父层级对象Id
     * @param workflowid 流程模板Id
     * @param parentrank 标识位
     * @return 结果
     */
   /* public int updateorderforupdate(Integer level,Long parentid,Long workflowid,String parentrank){
        RdaNodeTemplete rdaNodeTemplete=new RdaNodeTemplete();
        if(level>0 && parentid>0){
            RdaNodeTemplete NodeTemplete=selectRdaNodeTempleteById(parentid);
            parentrank=NodeTemplete.getRank();
        }
        rdaNodeTemplete.setParentid(parentid);
        rdaNodeTemplete.setProjectid(workflowid);
        List<RdaNodeTemplete>list=selectRdaNodeTempleteList(rdaNodeTemplete);
        int i=0;
        for (RdaNodeTemplete node:list) {
            i++;
            String newrank;
            if(node.getLevel()==1 || parentrank==null || "".equals(parentrank)){
                newrank= String.valueOf(i);
            }else{
                newrank= parentrank.trim()+"."+String.valueOf(i).trim();
            }
            RdaNodeTemplete newNode=new RdaNodeTemplete();
            newNode.setId(node.getId());
            if(node.getRank()==null || !node.getRank().equals(newrank)){
                newNode.setRank(newrank);
                updateRdaNodeTemplete(newNode);
            }
            if(node.getRdorder()!=null || !node.getRdorder().equals(i)){//序号
                newNode.setRdorder(i);
            }
            int num=updateRdaNodeTemplete(newNode);
            if(num>0){
                updateorderforupdate(node.getLevel(),node.getId(),node.getProjectid(),newrank);
            }
        }
        return 0;
    }*/

    /**
     * 转换字符串数组到Long数组
     *
     * @param strArray
     * @return Long[]
     * @throws
     */
    public Long[] getLongArrayFromStringArray(String[] strArray){
        if(strArray == null){
            return new Long[0];
        }
        Long[] result=new Long[strArray.length];
        for (int i = 0; i < result.length; i++) {
            result[i]=Long.valueOf(strArray[i]);
        }
        return result;
    }

    @Override
    public List<RdaNodeTemplete> selectRdaNodeTempleteAgentList(Long workflowid, String isAgent) {
        return rdaNodeTempleteMapper.selectRdaNodeTempleteAgentList(workflowid,isAgent);
    }

    @Override
    public Long selectRdaNodeTempleteNextval() {
        return rdaNodeTempleteMapper.selectRdaNodeTempleteNextval();
    }

    @Override
    public int deleteRdaNodeTempleteByWorkflowid(Long workflowid) {
        return rdaNodeTempleteMapper.deleteRdaNodeTempleteByWorkflowid(workflowid);
    }

    @Override
    public int insertRdaNodeTempleteFlowChartAdd(RdaNodeTemplete rdaNodeTemplete) {
        Long userId = SecurityUtils.getUserId();
        rdaNodeTemplete.setOwnerid(userId.intValue());
        rdaNodeTemplete.setTypeid(WorkflowStateid.nodeTempleteTypeid.intValue());
        rdaNodeTemplete.setPolicyid(WorkflowStateid.nodeTempletePolicyid.intValue());
        rdaNodeTemplete.setStateid(WorkflowStateid.nodeTempleteCreateid.intValue());

        List<RdaNodeTemplete> list=rdaNodeTempleteMapper.selectRdaNodeTempleteByWorkflowid(rdaNodeTemplete.getWorkflowid());
        RdaNodeTemplete rdaNodeTempleteEnd=rdaNodeTempleteMapper.selectRdaNodeTempleteByNodeType(rdaNodeTemplete.getWorkflowid(),-1l);
        rdaNodeTemplete.setNodeType(1);
        if(rdaNodeTempleteEnd!=null){
            rdaNodeTemplete.setLevel(rdaNodeTempleteEnd.getLevel());
        }
        if("1".equals(rdaNodeTemplete.getIsRejectTostart())){
            rdaNodeTemplete.setRejectTostart(true);
        }else{
            rdaNodeTemplete.setRejectTostart(false);
        }
        if("1".equals(rdaNodeTemplete.getIsRejectAutomatic())){
            rdaNodeTemplete.setRejectAutomatic(true);
        }else{
            rdaNodeTemplete.setRejectAutomatic(false);
        }
        int num=rdaNodeTempleteMapper.insertRdaNodeTemplete(rdaNodeTemplete);
        if(rdaNodeTempleteEnd!=null){
            RdaNodeTemplete updateLevel=new RdaNodeTemplete();
            updateLevel.setId(rdaNodeTempleteEnd.getId());
            updateLevel.setLevel(list.size()+1);
            rdaNodeTempleteMapper.updateRdaNodeTemplete(updateLevel);
        }
        return num;
    }
}
